import React, { Component } from 'react';
import 'styles/expense/expense-common-table.scss';
import ResizeTable from 'components/resize-table';
import ExpenseMainService from './expense-main-service';
import TablesHoc from '../component/tables-hoc';
import { queryCurrencyPrecision, messages } from 'share/common';
import Annotate from 'components/template/annotate';
import ExpenseService from '../expense-service';
import { connect } from 'react-redux';
import ApplicationApportion from '../../my-account/components/application-apportion';
import shallowEqual from '../component/shallowEqual';

@TablesHoc
@connect(mapStateToProps)
class ExpenseTable extends Component {

  static contextTypes = {
    annotates: React.PropTypes.array,
    isWaitForAudit: React.PropTypes.bool,
    currentExpense: React.PropTypes.object,
    expenseReport: React.PropTypes.object,
    currentExpenseType: React.PropTypes.object,
  };

  constructor(props, context) {
    super(props, context);
    this.state = {
      ...this.init(props, context)
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    nextProps.randomHash !== this.props.randomHash && this.setState({ ...this.init(nextProps, nextContext) }, () => this.tableRef.refreshTableColumns(['render']));
  }

  shouldComponentUpdate(nextProps, nextState, nextContext) {
    return !shallowEqual(this.props, nextProps) ||
      !shallowEqual(this.state, nextState) ||
      !shallowEqual(this.context, nextContext);
  }

  init = (props, context) => {
    return {
      columns: ExpenseMainService.columns.get(props.tableFlag)
        .map(item => {
          item.dataIndex === 'amount' && (item.render = (value) => React.Component.prototype.filterMoney(value, queryCurrencyPrecision(props.currency)));
          item.dataIndex === 'operate' && (item.render = (value, record) =>
              props.data.some(item => !!item.applicationApportionmentId)
              && <ApplicationApportion
                flag='icon'
                invoiceOID={context.currentExpense.invoiceOID}
                expenseReportOID={context.expenseReport.expenseReportOID}
                applicationApportionmentIds={record.applicationApportionmentIds}
              />
          );
          return item;
        }),
      annotates: context.annotates
    };
  };

  handleAnnotate = async () => {
    const { currentExpense: { invoiceOID } } = this.context;
    const annotates = await ExpenseService.getAnnotate(invoiceOID);
    this.setState({ annotates });
  };

  render() {
    const { icon, data, tableFlag, expandedRowRender, onRow, loginUser, keyFlag, rowClassName } = this.props;
    const { currentExpense: { id }, isWaitForAudit } = this.context;
    const { columns, annotates } = this.state;
    return (
      <section className="expense-common-table">
        <Annotate
          params={{
            typeName: 'INVOICE',
            entityID: id,
            target: { type: tableFlag, key: keyFlag }
          }}
          disabled={!isWaitForAudit}
          annotateList={ExpenseService.getAnnotateList(keyFlag || tableFlag, annotates, loginUser)}
          onChange={this.handleAnnotate}
          iconStyle={{
            position: 'absolute',
            left: '450px',
            top: '8px'
          }}
        >
          <div
            className={`expense-common-table-content ${isWaitForAudit ? 'expense-table-annotate' : ''}`}>
            <div
              className={`expense-common-table-header ${isWaitForAudit ? 'expense-table-annotate-header' : ''}`}>
              <div className="expense-common-table-info">
                <img src={icon.src} alt={icon.name}/>
                <span className="expense-common-table-text">{icon.name}</span>
              </div>
              <div className="expense-common-table-num">
                {messages('expense-1.key703', { arg1: data ? data.length : 0 })/*共{arg1}条*/}
              </div>
            </div>
            <ResizeTable
              tableName={tableFlag}
              columns={columns}
              dataSource={data}
              scroll={{ x: 'max-content' }}
              pagination={false}
              tableFlag
              onRow={onRow}
              rowKey={'id'}
              expandedRowRender={expandedRowRender}
              rowClassName={rowClassName}
              onRef={ref => this.tableRef = ref}
            />
          </div>
        </Annotate>
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    currentExpense: state.expense.currentExpense,
    loginUser: state.login.loginUser
  };
}

export default ExpenseTable;
